package com.atmilan.quartz.utils.product;

import com.alibaba.fastjson.JSONObject;
import com.atmilan.quartz.config.RestTemplateConfig;
import com.atmilan.quartz.model.dto.orange.OrangeProductResDTO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * 拉取商品源数据
 */

@Slf4j
@Service
public class OrangeProductUtil {

    @Autowired
    private RestTemplateConfig restTemplateConfig;

    @Value("${orange.url}")
    private String orangeUrl;
    @Value("${orange.appId}")
    private String orangeAppId;
    @Value("${orange.secret}")
    private String orangeSecret;

    /**
     * 获取orange商品列表
     * @param page
     * @param limit
     * @return
     */
    public OrangeProductResDTO getOrangeProductList(int page, int limit) throws JsonProcessingException {
        OrangeProductResDTO orangeProductResDTO = null;
        try {
            StringBuilder sb = new StringBuilder().append(orangeUrl)
                    .append("item/get_item_list.do");
            JSONObject param = new JSONObject();
            param.put("appId",orangeAppId);
            param.put("limit",limit);
            param.put("page",page);
            String sign = DigestUtils.md5Hex(param.toJSONString()+orangeSecret).toUpperCase();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.add("SIGN", sign);
            HttpEntity<JSONObject> requestEntity = new HttpEntity<>(param, headers);
            RestTemplate restTemplate = restTemplateConfig.restTemplate();
            ResponseEntity<String> response = restTemplate.postForEntity(sb.toString(), requestEntity, String.class);
            if (HttpStatus.OK != response.getStatusCode()) {
                JSONObject message = JSONObject.parseObject(response.getBody());
                String errorMessage = message.getString("error");
                log.info("--------------- 获取orange商品列表异常{} ---------------", errorMessage);
            }
            ObjectMapper mapper = new ObjectMapper();
            orangeProductResDTO = mapper.readValue(response.getBody(), OrangeProductResDTO.class);
        }catch (Exception e){
            e.printStackTrace();
        }
        return orangeProductResDTO;
    }

}
